<template>
  <div>
    <div v-loading="teamInfoLoading">
      <el-row>
        <el-col :span="20">
          <el-divider content-position="left">
            <span style="font-size: 16px;color: #353434;font-weight: bold;">基本信息</span>
          </el-divider>
        </el-col>
        <el-col :span="4" class="gl_pt_10 gl_pl_10">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditTeamInfo">编辑信息</el-button>
        </el-col>
      </el-row>
      <!-- 基本信息 -->
      <el-row v-loading="teamInfoLoading" class="team_info">
        <el-col :span="3" align="left">
          <div class="team_info_img">
            <img class="show_img" :src="getStaticAvatarUrl(teamInfo.imagePath)">
          </div>
        </el-col>
        <el-col :span="21">
          <el-row style="margin-bottom: 8px;">
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">团体名称：</span>
              <span class="label_content">{{ teamInfo.name }}</span>
            </el-col>
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">团体简称：</span>
              <span class="label_content">{{ teamInfo.shortName }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">团体类型：</span>
              <span class="label_content">{{ teamInfo.delegationType && teamInfo.delegationType.name }}</span>
            </el-col>
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">所在地区：</span>
              <span class="label_content">{{ addressDataForCheck(teamInfo) }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="16" class="gl_ellipsis">
              <span class="label_name">团体地址：</span>
              <span class="label_content">{{ teamInfo.address }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">联系人：</span>
              <span class="label_content">{{ teamInfo.contactPerson }}</span>
            </el-col>
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">联系方式：</span>
              <span class="label_content">{{ teamInfo.phoneNumber }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">中跆协会员号：</span>
              <span class="label_content">{{ teamInfo.ctkCode }}</span>
            </el-col>
            <el-col :span="8" class="gl_ellipsis">
              <span class="label_name">省跆协会员号：</span>
              <span class="label_content">{{ teamInfo.ptkCode }}</span>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <!-- 快捷入口 -->
    <el-row>
      <el-col :span="20">
        <el-divider content-position="left">
          <span style="font-size: 16px;color: #353434;font-weight: bold;">人员管理</span>
        </el-divider>
      </el-col>
      <el-col :span="4" class="gl_pt_10 gl_pl_10">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEnterToMember()">人员管理</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col v-for="item in dict.registerTagType" :key="item.code" :span="5">
        <el-button class="member_tags_nav" type="default" size="mini" @click="handleEnterToMember(item.code)">{{ item.value }}</el-button>
      </el-col>
    </el-row>
    <el-dialog class="gl_dialog_TitleLine" title="编辑" :visible.sync="dialogVisibleForTeam" :close-on-click-modal="false" width="1200px">
      <delegation-info
        ref="refDelegationInfo"
        :team-data="teamInfo"
        :is-default-check="teamInfo.isApproved"
        :organization-units-types="dict.delegationType"
      />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleForTeam = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" :loading="addBtnLoadding" type="primary" @click="submitTeamInfo">{{ $t('button.submit') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { loginOidc } from '@/lib/oidc_fun';
import {
  api_GET_EventsManagementDelegationId,
  api_PUT_EventsManagementDelegationId,
  api_POST_EventsManagementDelegation
} from '@/extend/api/gameswaggerApi/app';
import delegationInfo from '@/components/DelegationInfo';
import { getToken } from '@/lib/auth';
export default {
  components: {
    delegationInfo
  },
  data() {
    return {
      teamInfoLoading: false,
      teamInfo: {},
      dialogVisibleForTeam: false,
      organizationUnitsTypes: [],
      addBtnLoadding: false,
      tagsColorTheme: ['primary', 'success', 'info', 'warning']
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      currentUserType: state => state.user.currentUserType
    })
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getTeamInfo();
        this.organizationUnitsTypes = [{ code: 'Club', name: '道馆' }];
      }
    }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    if (this.currentUserType) {
      this.getTeamInfo();
      this.organizationUnitsTypes = [{ code: 'Club', name: '道馆' }];
    }
    console.log(getToken());
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取团体信息
    getTeamInfo(delegationId) {
      if (!this.currentUserType.delegationId && !delegationId) return;
      api_GET_EventsManagementDelegationId(
        this.currentUserType.delegationId || delegationId,
        { IncludeDelegationType: true }
      ).then(res => {
        this.teamInfo = res;
        console.log(this.teamInfo);
        this.$store.dispatch('user/getCurrentUserTeamInfo', res);
      }, error => {
        this.$message({ type: 'error', message: '获取团体信息失败！' + (error.error && error.error.message || '') });
      });
    },
    openEditTeamInfo() {
      this.dialogVisibleForTeam = true;
    },
    // 提交团体信息
    submitTeamInfo() {
      this.$refs.refDelegationInfo.getInsideTeamData()
        .then(
          res => {
            const _delegationId = this.currentUserType.delegationId;
            if (_delegationId) {
              this.updateDelegationInfo(res);
            } else {
              this.createDelegationInfo(res);
            }
          }
        )
        .catch(
          error => {
            console.log('updateDelegationInfo -> error', error);
          }
        );
    },
    // 更新团体信息
    updateDelegationInfo (data) {
      this.addBtnLoadding = true;
      api_PUT_EventsManagementDelegationId(this.currentUserType.delegationId, data)
        .then(
          res => {
            this.addBtnLoadding = false;
            this.dialogVisibleForTeam = false;
            this.$message({ type: 'success', message: '操作成功' });
            this.getTeamInfo();
          }
        )
        .catch(
          error => {
            this.addBtnLoadding = false;
            this.$message({ type: 'error', message: '修改团体信息失败' });
            console.log('updateDelegationInfo -> error', error);
          }
        );
    },
    // 创建一个团体
    createDelegationInfo (data) {
      this.addBtnLoadding = true;
      api_POST_EventsManagementDelegation(data)
        .then(
          res => {
            this.addBtnLoadding = true;
            this.dialogVisibleForTeam = false;
            this.$message({ type: 'success', message: '操作成功' });
            // 更新账号信息
            this.$store.dispatch('user/getInfo');
            this.$store.dispatch('user/getCurrentUserType');
            const href = window.location.href;
            console.log(getToken());
            loginOidc({
              state: window.btoa(href)
            });
            this.getTeamInfo(res.id);
          }
        )
        .catch(
          error => {
            this.addBtnLoadding = false;
            this.$message({ type: 'error', message: `创建团体信息失败${'，' + error.error.message || ''}` });
            console.log('updateDelegationInfo -> error', error);
          }
        );
    },
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    handleEnterToMember(role) {
      this.$router.push({
        path: '/myCenter/team/member',
        query: { role: role || '' }
      });
    },
    addressDataForCheck (data) {
      const _provinceCode = data.provinceCode;
      const _cityCode = data.cityCode;
      const _countyCode = data.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    }
  }
};
</script>
<style>
.team_info_img .show_img {
  width: 105px;
  height: 105px;
}
.edit_team {
  font-weight: bold;
  cursor: pointer;
}
.edit_member {
  font-weight: bold;
  cursor: pointer;
  line-height: 37px;
}
.label_name {
  font-size: 14px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.8);
}
.label_content {
  color: #333;
  font-size: 14px;
}
.member_tags_nav {
  width: 100%;
  line-height: 70px;
  font-size: 18px;
  color: #000;
}
</style>
